﻿using CL.IO.Zip;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Diagnostics;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace UnZipWithProcess
{
    public partial class Form1 : Form
    {
        bool FirstActivated = false;
        public Form1()
        {
            InitializeComponent();
            this.Shown += Form1_Shown;
        }

        /// <summary>
        /// 读取命令行参数，执行解压
        /// D:\JQ\Source\JQPACS2018\RIS.UI\bin\Debug\package\ZipExtractor.exe
        /// C:\Users\stardance\AppData\Local\Temp\7.0.0.2.zip 
        /// D:\JQ\Source\JQPACS2018\RIS.UI\bin\Debug\RIS.UI.exe
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>

        private void Form1_Shown(object sender, EventArgs e)
        {
            if (FirstActivated) return;
            string[] args = Environment.GetCommandLineArgs();

            FirstActivated = true;

            if (!args.Any())
            {
                throw new ArgumentException("解压缩参数为空！");//MessageBox.Show("参数异常！", "警告", MessageBoxButtons.OK, MessageBoxIcon.Error);
                //return;
            }


            foreach (var process in Process.GetProcesses())
            {
                try
                {
                    if (process.MainModule.FileName.Equals(args[2]))
                    {
                        label1.Text = "等待当前主程序退出";
                        process.Kill();
                    }
                }
                catch (Exception exception)
                {
                    Debug.WriteLine(exception.Message);
                }
            }

            //File.WriteAllText(@"D:\PrintArgs.txt",string.Join("\r\n",args));

           
            ZipHandler handler = ZipHandler.GetInstance();
            string dir = Path.GetDirectoryName(args[2]);
            handler.UnpackAll(args[1], dir, process =>
            {
                progressBar1.Value = (int)process;
            });

            label1.Text = "解压完成！";

            label1.Text = "尝试重启程序";
            


            if (!File.Exists(args[2]))
            {
                MessageBox.Show("重启程序失败，请手动重启");
                Application.Exit();
            }
            var info = new ProcessStartInfo(args[2]);
            Process.Start(info);

            Application.Exit();
        }
    }
}
